﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CoreApp.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;

namespace CoreApp.Web.Controllers
{
    /*  
        redis缓存
     */
    public class RedisController : ParentController
    {
        private IDistributedCache redisCache;
        public RedisController(IDistributedCache _redisCache)
        {
            redisCache = _redisCache;
        }

        public async Task<IActionResult> Index()
        {
            try
            {
                //插入值                
                string name = "Tom";

                //插入并设置过期时间为20分钟
                // await redisCache.SetAsync("name", Encoding.UTF8.GetBytes(name),
                //                             new DistributedCacheEntryOptions()
                //                             {
                //                                 AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(20)
                //                             });

                //await redisCache.SetStringAsync("name",name);//不带设置过期时间
                //带设置过期时间
                await redisCache.SetStringAsync("name", name,
                                                    new DistributedCacheEntryOptions()
                                                    {
                                                        AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(20)
                                                    }
                                                );


                //获取值
                string myName = await redisCache.GetStringAsync("name");
            }
            catch (Exception ex)
            {
                NLogHelper.Error(ex);
            }

            return View();
        }
    }
}